package com.zyk.scaffold.oauth.config.oauth.grant;

import com.zyk.scaffold.oauth.config.oauth.support.LocalUserDetailsService;
import com.zyk.scaffold.oauth.framework.OauthManager;
import com.zyk.scaffold.oauth.framework.domain.*;
import com.zyk.scaffold.oauth.framework.interfaces.ITokenGranter;
import com.zyk.scaffold.common.utils.AssertUtil;
import com.zyk.scaffold.common.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TenantRefreshGranter implements ITokenGranter {

    public static final String TENANT_CODE = "tenantCode";
    public static final String ACCESS_TOKEN = "accessToken";

    private String grantType = "tenant_refresh";
    private OauthManager oauthManager;
    private LocalUserDetailsService localUserDetailsService;
    public TenantRefreshGranter(OauthManager oauthManager, LocalUserDetailsService localUserDetailsService) {
        log.info("TenantRefreshTokenGranter created!");
        this.oauthManager = oauthManager;
        this.localUserDetailsService = localUserDetailsService;
    }

    @Override
    public OauthContext grant(OauthRequest request) {
        String tenantCode = MapUtils.getString(request.getRequestParam(), TENANT_CODE);
        String accessToken = MapUtils.getString(request.getRequestParam(), ACCESS_TOKEN);
        AssertUtil.notEmptyString(tenantCode, "租户编码不能为空");
        AssertUtil.notEmptyString(accessToken, "accessToken不能为空");
        AccessToken accessTokenObj = oauthManager.getAccessToken(accessToken);
        AssertUtil.notNull(accessTokenObj, "accessToken不存在,登录失败");
        ClientDetails clientDetails = this.oauthManager.getClientDetailsService().loadClientDetailsByClientId(accessTokenObj.getClientId());
        AssertUtil.notNull(clientDetails, "客户端不存在,禁止登录");
        UserDetails userDetails = localUserDetailsService.loadTenantUserDetails(accessTokenObj.getAccount(), tenantCode);
        AssertUtil.notNull(userDetails, "账号不存在,禁止登录");
        OauthContext oauthContext = new OauthContext(userDetails, request, clientDetails);
        return oauthContext;
    }

    @Override
    public String getGrantType() {
        return grantType;
    }
}
